package com.jiumi.api.controller;


import cn.hutool.core.util.NumberUtil;
import com.jiumi.api.base.BaseApiController;
import com.jiumi.api.entity.SysUserDo;
import com.jiumi.api.util.WeiXinUtil;
import com.jiumi.api.vo.WxLoginVo;

import com.jiumi.baseconfig.domain.*;
import com.jiumi.baseconfig.service.*;
import com.jiumi.common.core.domain.AjaxResult;
import com.jiumi.common.core.domain.entity.SysUser;
import com.jiumi.common.core.domain.model.LoginUser;
import com.jiumi.common.core.page.TableDataInfo;
import com.jiumi.common.core.redis.RedisCache;
import com.jiumi.common.utils.DateUtils;
import com.jiumi.common.utils.SecurityUtils;
import com.jiumi.common.utils.StringUtils;
import com.jiumi.config.WeiXinConfig;
import com.jiumi.framework.web.service.UserInfo;
import com.jiumi.system.domain.SysNotice;
import com.jiumi.system.service.ISysConfigService;
import com.jiumi.system.service.ISysNoticeService;
import io.swagger.annotations.ApiOperation;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.NumberUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author lun.zhang
 * @create 2022/10/18 18:29
 */
@RestController
@RequestMapping("/api")
public class UserApiController extends BaseApiController {

    @Autowired
    private WeiXinConfig weiXinConfig;
    @Autowired
    private WeiXinUtil weiXinUtil;
    @Autowired
    private IBaseUserService userInfoService;


    @Autowired
    private IBaseGoodsService baseGoodsService;

    @Autowired
    private IBaseOrderExchangeService baseOrderExchangeService;

    @Autowired
    private IBaseFeedbackService feedbackService;
    @Autowired
    private IScoreHistoryService scoreHistoryService;

    @Autowired
    private IBaseAppointmentService baseAppointmentService;

    @Autowired
    private IBaseContractService baseContractService;

    @Autowired
    private IBaseUserClockService baseUserClockService;

    @Autowired
    private IBaseCompanyService baseCompanyService;

    @Autowired
    private IBaseCompanyAddressService baseCompanyAddressService;

    @Autowired
    private IBusinessConfigService businessConfigService;

    @Autowired
    private IBaseUserResumeService baseUserResumeService;

    @Autowired
    private IUserEvaluateService userEvaluateService;

    @Autowired
    private IBaseUserFocusService baseUserFocusService;

    @Autowired
    private IBaseUserIntentionService baseUserIntentionService;

    @Autowired
    private IBaseUserIntentionCityService baseUserIntentionCityService;

    @Autowired
    private IUserMessageService userMessageService;

    @Autowired
    private ISysNoticeService noticeService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IBaseCompanyAccountService baseCompanyAccountService;

    @Autowired
    private IBaseUserResumeCertificateService baseUserResumeCertificateService;

    @Autowired
    private IBaseUserResumeExperienceService baseUserResumeExperienceService;
    @Autowired
    private ISysConfigService configService;

    /**
     * 获取微信手机号
     *
     * @param wxLoginVo wx登录签证官
     * @return {@link AjaxResult}
     */
    @PostMapping("/user/getWxPhoneNumber")
    public AjaxResult getPhoneNumberV2(@RequestBody WxLoginVo wxLoginVo) {
        return AjaxResult.success("", weiXinUtil.getWxPhoneNumber(wxLoginVo.getCode()));

    }


    /**
     * 更新用户信息
     *
     * @param userInfo
     * @return {@link AjaxResult}
     */
    @PostMapping("/user/updateUserInfo")
    public AjaxResult updateUserDetail(@RequestBody BaseUser userInfo) {
        Long userId = getUserId();
        userInfo.setUserId(userId);
        userInfo.setPassword(null);
        userInfo.setOpenId(null);
        int result = userInfoService.updateBaseUser(userInfo);
        return toAjax(result);

    }

    @GetMapping("/user/getUserDetail")
    public AjaxResult getUserDetail() {
        Long userId = getUserId();
        BaseUser userInfo = userInfoService.selectBaseUserByUserId(userId);
        userInfo.setPassword("");
        if(userInfo.getAuthUserId()!=null){
            userInfo.setAuthUser(userInfoService.selectBaseUserByUserId(userInfo.getAuthUserId()));
        }else{
            userInfo.setAuthUser(null);
        }
        BaseUser invteUser= userInfoService.selectUserByReferrerCode(userInfo.getInviteCode());
        if(invteUser!=null){
            userInfo.setInviteUserName(invteUser.getNickName());
            userInfo.setInviteUserCompany(invteUser.getCompanyName());
        }
        BaseUserIntention intention=baseUserIntentionService.selectBaseUserIntentionByUserId(userId);

        if(intention!=null){
            BaseUserIntentionCity param=new BaseUserIntentionCity();
            param.setIntentionId(intention.getId());
            List<BaseUserIntentionCity> cityList=baseUserIntentionCityService.selectBaseUserIntentionCityList(param);
            intention.setCityList(cityList);
        }else{
            intention=new BaseUserIntention();
        }
        if("01".equals(userInfo.getUserType()) || "02".equals(userInfo.getUserType()) ||"05".equals(userInfo.getUserType())){
            BaseCompany company= baseCompanyService.selectBaseCompanyById(userInfo.getCompanyId());
            userInfo.setAuthCompany(company);
        }
        userInfo.setIntention(intention);
        return AjaxResult.success(userInfo);
    }

    @ApiOperation("获取用户认证信息")
    @GetMapping("/userAuthInfo")
    public AjaxResult userAuthInfo(@RequestParam(value = "userId", required = true) Long userId) {
        BaseUser userInfo = userInfoService.selectBaseUserByUserId(userId);
        if("01".equals(userInfo.getUserType()) || "02".equals(userInfo.getUserType()) ||"05".equals(userInfo.getUserType())){
            BaseCompany company= baseCompanyService.selectBaseCompanyById(userInfo.getCompanyId());
            if(company!=null){
                BaseCompanyAddress param=new BaseCompanyAddress();
                param.setCompanyId(company.getId());
                List<BaseCompanyAddress> addressList= baseCompanyAddressService.selectBaseCompanyAddressList(param);
                company.setAdddressList(addressList);
                userInfo.setAuthCompany(company);
            }else{
                userInfo.setAuthCompany(null);
            }
        }
        return AjaxResult.success(userInfo);
    }

    @ApiOperation("用户使用积分兑换商品")
    @GetMapping("/userExchangeGoods")
    public AjaxResult userExchangeGoods(@RequestParam(value = "goodsId", required = true) Long goodsId,
                                        @RequestParam(value = "userName", required = false) String userName,
                                        @RequestParam(value = "phone", required = false) String phone,
                                        @RequestParam(value = "goodsNum", required = true) int goodsNum,
                                        @RequestParam(value = "address", required = false) String address) {
        BaseGoods goods = baseGoodsService.selectBaseGoodsById(goodsId);
        if (goods == null) {
            return AjaxResult.error("您要兑换的商品不存在");
        }
        if(goodsNum<=0){
            return AjaxResult.error("商品数量不能少于1个");
        }
        UserInfo loginUser = getLoginUser();
        BaseUser currentUser = userInfoService.selectBaseUserByUserId(loginUser.getUserId());
        int orderAmount=goodsNum*goods.getPrice().intValue();
        if(currentUser.getScoreAmount()==null){
            return AjaxResult.error("您的积分余额不足!");
        }
        if (currentUser.getScoreAmount().intValue() < orderAmount) {
            return AjaxResult.error("您的积分余额不足!");
        }
        int result = baseOrderExchangeService.userExchangeGoods(goods,goodsNum, currentUser, userName, phone, address);
        return toAjax(result);
    }

    @ApiOperation("用户积分兑换记录")
    @GetMapping("/userExchangeList")
    public TableDataInfo userExchangeList(BaseOrderExchange userExchangeReward) {
        BaseUser loginUser = getLoginUser().getUserInfo();
        userExchangeReward.setUserId(loginUser.getUserId());
        startPage();
        List<BaseOrderExchange> exchangeList = baseOrderExchangeService.selectBaseOrderExchangeList(userExchangeReward);
        return getDataTable(exchangeList);
    }

    @PostMapping("/feedBack/add")
    public AjaxResult addInfo(@Validated @RequestBody BaseFeedback feedback) {
        BaseUser userInfo = userInfoService.selectBaseUserByUserId(getUserId());
        feedback.setUserId(getUserId());
        feedback.setPhone(userInfo.getPhonenumber());
        feedback.setCreateTime(DateUtils.getNowDate());
        feedback.setCreateBy(userInfo.getUserName());
        feedback.setStatus("01");
        return AjaxResult.success(feedbackService.insertBaseFeedback(feedback));

    }


    @GetMapping("/user/getScoreHistory")
    public TableDataInfo getScoreHistory(ScoreHistory scoreHistory) {
        scoreHistory.setUserId(getUserId());
        startPage();
        startOrderBy();
        List<ScoreHistory> scoreHistories = scoreHistoryService.selectScoreHistoryList(scoreHistory);
        return getDataTable(scoreHistories);
    }

    @GetMapping("/user/getUserFocus")
    public TableDataInfo getUserFocus(BaseUserFocus userFocus) {
        if("01".equals(userFocus.getType())){
            BaseUserResume param=new BaseUserResume();
            param.setUserId(getUserId());
            startPage();
            List<BaseUserResume> resumeList= baseUserResumeService.selectUserFocusResumeList(param);
            return getDataTable(resumeList);
        }
        else if("02".equals(userFocus.getType())){
            BaseAppointment param=new BaseAppointment();
            param.setUserId(getUserId());
            startPage();
            List<BaseAppointment> userList= baseAppointmentService.selectUserFocusAppointmentList(param);
            return getDataTable(userList);
        }
        else{
            return getDataTable(new ArrayList<>());
        }
    }

    @GetMapping("/user/getUserInviteList")
    public TableDataInfo getUserInviteList(BaseUser userInfo) {
        String referrerCode= getLoginUser().getUserInfo().getReferrerCode();
        userInfo.setReferrerCode(referrerCode);
        startPage();
        List<BaseUser> userList = userInfoService.selectUserInviteList(userInfo);
        TableDataInfo req= getDataTable(userList);
        req.setMsg(referrerCode);
        return req;
    }

    @PostMapping("/user/saveAppointment")
    public AjaxResult saveAppointmentInfo(@Validated @RequestBody BaseAppointment appointment) {

        if(StringUtils.isEmpty(appointment.getUserPhone())){
            return AjaxResult.error("手机号不能为空");
        }
        if(appointment.getId()!=null) {
            BaseAppointment currentAppointment = baseAppointmentService.selectBaseAppointmentById(appointment.getId());
            if(currentAppointment==null){
                return AjaxResult.error("预约记录不存在");
            }
            if (currentAppointment.getUserId().intValue() != getUserId().intValue()) {
                return AjaxResult.error("您没有权限操作");
            }
        }
        BaseUser currentUser=getLoginUser().getUserInfo();
        BaseUser userinfo= userInfoService.selectUserByUserName(appointment.getUserPhone());
        if(("01".equals(currentUser.getUserType()) || "02".equals(currentUser.getUserType()) || "05".equals(currentUser.getUserType())) && userinfo==null){
            userinfo=new BaseUser();
            userinfo.setUserName(appointment.getUserPhone());
            userinfo.setNickName("");
            userinfo.setPhonenumber(appointment.getUserPhone());
            userinfo.setAddress(appointment.getUserAddress());
            //userinfo.setInviteCode(currentUser.getReferrerCode());
            if("03".equals(currentUser.getUserType())){
                userinfo.setAuthUserId(currentUser.getAuthUserId());
            }else{
                userinfo.setAuthUserId(currentUser.getUserId());
            }
            userinfo.setPublishType("02");
            userinfo.setCompanyId(currentUser.getCompanyId());
            userinfo.setCompanyName(currentUser.getCompanyName());
            userinfo.setCreateBy(currentUser.getUserName());
            userinfo.setCreateTime(DateUtils.getNowDate());
            userinfo.setUserType("03");
            userInfoService.insertBaseUser(userinfo);
        }
        String appointmentCode=DateUtils.dateTimeNow()+ ThreadLocalRandom.current().nextInt(1000);
        appointment.setCode(appointmentCode);
        appointment.setUserId(getUserId());
        appointment.setApplyTime(DateUtils.getNowDate());
        appointment.setApplyStatus("01");
        appointment.setUpdateTime(DateUtils.getNowDate());
        appointment.setUpdateBy(getUsername());
        if(appointment.getId()==null){
            appointment.setCreateTime(DateUtils.getNowDate());
            appointment.setCreateBy(getUsername());
        }
        return baseAppointmentService.saveBaseAppointment(appointment);
    }

    @GetMapping("/user/refreshAppointment")
    public AjaxResult refreshAppointment(@RequestParam(value = "id", required = true) Long id) {
        BaseAppointment currentAppointment= baseAppointmentService.selectBaseAppointmentById(id);
        if(currentAppointment.getUserId().intValue()!=getUserId().intValue()){
            return AjaxResult.error("您没有权限操作");
        }
        BaseAppointment appointment=new BaseAppointment();
        appointment.setId(id);
        appointment.setApplyTime(DateUtils.getNowDate());
        appointment.setUpdateTime(DateUtils.getNowDate());
        appointment.setUpdateBy(getUsername());
        int result= baseAppointmentService.updateBaseAppointment(appointment);
        return toAjax(result);
    }

    @GetMapping("/user/removeAppointment")
    public AjaxResult removeAppointment(@RequestParam(value = "id", required = true) Long id) {
        BaseAppointment appointment= baseAppointmentService.selectBaseAppointmentById(id);
        if("01".equals(appointment.getApplyStatus())){
            return AjaxResult.error("预约记录还在生效中");
        }
        if(appointment.getUserId().intValue()!=getUserId().intValue()){
            return AjaxResult.error("您没有权限操作");
        }
        int result= baseAppointmentService.deleteBaseAppointmentById(id);
        return toAjax(result);
    }

    @GetMapping("/user/offlineAppointment")
    public AjaxResult offlineAppointment(@RequestParam(value = "id", required = true) Long id,@RequestParam(value = "status", required = false,defaultValue = "02") String status) {
        BaseAppointment appointment= baseAppointmentService.selectBaseAppointmentById(id);
        if(appointment.getUserId().intValue()!=getUserId().intValue()){
            return AjaxResult.error("您没有权限操作");
        }
        appointment.setApplyStatus(status);
        appointment.setApplyTime(DateUtils.getNowDate());
        appointment.setCreateTime(DateUtils.getNowDate());
        appointment.setUpdateTime(DateUtils.getNowDate());
        appointment.setUpdateBy(getUsername());
        int result= baseAppointmentService.updateBaseAppointment(appointment);
        return toAjax(result);
    }

    @GetMapping("/user/getUserAppointment")
    public TableDataInfo getUserAppointment(BaseAppointment appointment) {
        appointment.setUserId(getUserId());
        startOrderBy();
        startPage();
        List list=baseAppointmentService.selectBaseAppointmentList(appointment);
        return getDataTable(list);
    }

    @GetMapping("/user/getUserAppointmentByUserId")
    public TableDataInfo getUserAppointment(@RequestParam(value = "userId", required = true) Long userId) {
        BaseAppointment appointment=new BaseAppointment();
        appointment.setUserId(userId);
        startOrderBy();
        startPage();
        List list=baseAppointmentService.selectBaseAppointmentList(appointment);
        return getDataTable(list);
    }

    @GetMapping("/user/getAppointmentDetail")
    public AjaxResult getAppointmentDetail(@RequestParam(value = "id", required = true) Long id) {
        BaseAppointment appointment=baseAppointmentService.selectBaseAppointmentById(id);
        AjaxResult result= AjaxResult.success(appointment);
        BaseUser publishUser=userInfoService.selectBaseUserByUserId(appointment.getUserId());
        if(publishUser!=null){
            publishUser.setPassword(null);
        }
        result.put("publishUser",publishUser);
        result.put("focusFlag", 'N');

        try {
            BaseUser baseCurrentUser=getLoginUser().getUserInfo();
            BaseUser currentUser=userInfoService.selectBaseUserByUserId(baseCurrentUser.getUserId());
            String kefuPhone = configService.selectConfigByKey("sys.customer.phonenumber");
            if("04".equals(currentUser.getUserType())){
                if(currentUser.getAuthUserId()!=null){
                    BaseUser authUser= userInfoService.selectBaseUserByUserId(currentUser.getAuthUserId());
                    if(authUser!=null){
                        if(authUser.getUserId().intValue()==1){
                            authUser= userInfoService.selectBaseUserByUserId(1L);
                            authUser.setPhonenumber(kefuPhone);
                            authUser.setPassword(null);
                        }
                    }else{
                        authUser= userInfoService.selectBaseUserByUserId(1L);
                        authUser.setPhonenumber(kefuPhone);
                        authUser.setPassword(null);
                    }
                    authUser.setPassword(null);
                    result.put("authUser",authUser);
                }else{
                    BaseUser authUser= userInfoService.selectBaseUserByUserId(1L);
                    authUser.setPhonenumber(kefuPhone);
                    authUser.setPassword(null);
                    result.put("authUser",authUser);
                }
            }else{
                BaseUser authUser=null;
                if("01".equals(publishUser.getUserType()) || "02".equals(publishUser.getUserType()) || "05".equals(publishUser.getUserType())){
                    authUser= userInfoService.selectBaseUserByUserId(publishUser.getUserId());
                }else{
                    authUser= userInfoService.selectBaseUserByUserId(publishUser.getAuthUserId());
                }

                if(authUser!=null){
                    if(authUser.getUserId().intValue()==1){
                        authUser= userInfoService.selectBaseUserByUserId(1L);
                        authUser.setPhonenumber(kefuPhone);
                        authUser.setPassword(null);
                    }
                }else{
                    authUser= userInfoService.selectBaseUserByUserId(1L);
                    authUser.setPhonenumber(kefuPhone);
                    authUser.setPassword(null);
                }
                authUser.setPassword(null);
                result.put("authUser",authUser);
            }
            BaseUserFocus focus = new BaseUserFocus();
            focus.setUserId(currentUser.getUserId());
            focus.setFocusUserId(appointment.getId());
            focus.setType("02");
            List<BaseUserFocus> focusList = baseUserFocusService.selectBaseUserFocusList(focus);
            if (focusList.size() > 0) {
                result.put("focusFlag", 'Y');
            }
        }
        catch(Exception e){
            logger.info(e.getMessage());
        }
        return result;
    }

    @GetMapping("/user/setFocusUser")
    public AjaxResult setFocusUser(@RequestParam(value = "id", required = true) Long id,@RequestParam(value = "type", required = false,defaultValue = "01") String type) {
        BaseUser userInfo=userInfoService.selectBaseUserByUserId(id);
        BaseUserFocus focus=new BaseUserFocus();
        focus.setUserId(getUserId());
        focus.setType(type);
        focus.setFocusUserId(id);
        List<BaseUserFocus> focusList=baseUserFocusService.selectBaseUserFocusList(focus);
        if(focusList.size()>0){
            BaseUserFocus oldFocus=focusList.get(0);
            baseUserFocusService.deleteBaseUserFocusById(oldFocus.getId());
        }else{
            focus.setCreateTime(DateUtils.getNowDate());
            baseUserFocusService.insertBaseUserFocus(focus);
        }
        return AjaxResult.success("关注成功");
    }

    @GetMapping("/user/getAppointmentCount")
    public AjaxResult getAppointmentCount(BaseAppointment appointment) {
        appointment.setUserId(getUserId());
        appointment.setApplyStatus("01");
        List list=baseAppointmentService.selectBaseAppointmentList(appointment);
        AjaxResult result= AjaxResult.success();
        result.put("count",list.size());
        return result;
    }


    @GetMapping("/user/getEmployeeContract")
    public TableDataInfo getEmployeeContract(BaseContract contract) {
        BaseUser currentUser= getLoginUser().getUserInfo();
        BaseCompanyAccount param=new BaseCompanyAccount();
        param.setUserId(currentUser.getUserId());
        param.setCompanyId(currentUser.getCompanyId());
        param.setIsMain("Y");
        List<BaseCompanyAccount> account= baseCompanyAccountService.selectBaseCompanyAccountList(param);
        if(account.size()>0){
            contract.setIsAdmin("Y");
        }
        else{
            contract.setIsAdmin("N");
        }
        contract.setAuserId(getUserId());
        startPage();
        startOrderBy();
        List list=baseContractService.selectUserContractList(contract);
        return getDataTable(list);
    }

    @GetMapping("/user/getAuntContract")
    public TableDataInfo getAuntContract(BaseContract contract) {
        contract.setAuserId(getUserId());
        startPage();
        startOrderBy();
        List list=baseContractService.selectUserContractList(contract);
        return getDataTable(list);
    }

    @GetMapping("/user/getAgencyContract")
    public TableDataInfo getAgencyContract(BaseContract contract) {
        BaseUser currentUser= getLoginUser().getUserInfo();
        BaseCompanyAccount param=new BaseCompanyAccount();
        param.setUserId(currentUser.getUserId());
        param.setCompanyId(currentUser.getCompanyId());
        param.setIsMain("Y");
        List<BaseCompanyAccount> account= baseCompanyAccountService.selectBaseCompanyAccountList(param);
        if(account.size()>0){
            contract.setIsAdmin("Y");
        }
        else{
            contract.setIsAdmin("N");
        }
        contract.setAuserId(getUserId());
        startPage();
        startOrderBy();
        List list=baseContractService.selectUserContractList(contract);
        return getDataTable(list);
    }

    @GetMapping("/user/userClock")
    public AjaxResult userClock() {
        BaseUserClock clock=new BaseUserClock();
        clock.setUserId(getUserId());
        BaseUserClock clockInfo=baseUserClockService.selectLatestUserClockList(clock);
        BusinessConfig config=businessConfigService.selectBusinessConfigById(3L);
        if(clockInfo!=null){
            Long diffSecond=(DateUtils.getNowDate().getTime()-clockInfo.getClockTime().getTime())/1000;
            if(Long.valueOf(config.getValue())*60*60>=diffSecond){
                return AjaxResult.error("打卡时间间隔未达到"+config.getValue()+"小时");
            }
        }
        clock.setClockDate(DateUtils.dateTime());
        List<BaseUserClock>  list=baseUserClockService.selectBaseUserClockList(clock);
        if(list.size()>0){
            BaseUserClock oldClick=list.get(0);
            Long diffSeconds=(DateUtils.getNowDate().getTime()-oldClick.getClockTime().getTime())/1000;
            if(Long.valueOf(config.getValue())*60*60<=diffSeconds){
                clock.setClockTime(DateUtils.getNowDate());
                baseUserClockService.insertBaseUserClock(clock);
                BaseUser newUser=new BaseUser();
                newUser.setUserId(getUserId());
                newUser.setClickStatus("02");
                newUser.setClickTime(DateUtils.getNowDate());
                newUser.setUpdateBy(getUsername());
                newUser.setUpdateTime(DateUtils.getNowDate());
                userInfoService.updateBaseUser(newUser);
            }else{
                return AjaxResult.error("打卡时间间隔未达到"+config.getValue()+"小时");
            }
            return AjaxResult.success("打卡成功！");
        }
        clock.setClockTime(DateUtils.getNowDate());
        baseUserClockService.insertBaseUserClock(clock);
        BaseUser newUser=new BaseUser();
        newUser.setUserId(getUserId());
        newUser.setClickStatus("02");
        newUser.setClickTime(DateUtils.getNowDate());
        newUser.setUpdateBy(getUsername());
        newUser.setUpdateTime(DateUtils.getNowDate());
        userInfoService.updateBaseUser(newUser);
        return AjaxResult.success("打卡成功");
    }

    @GetMapping("/user/userHelpClock")
    public AjaxResult userHelpClock(@RequestParam(value = "userId", required = true) Long userId) {
        BaseUserClock clock=new BaseUserClock();
        clock.setUserId(userId);
        BaseUserClock clockInfo=baseUserClockService.selectLatestUserClockList(clock);
        BusinessConfig config=businessConfigService.selectBusinessConfigById(3L);
        if(clockInfo!=null){
            Long diffmin=(DateUtils.getNowDate().getTime()-clockInfo.getClockTime().getTime())/1000;
            if(Long.valueOf(config.getValue())*3600>=diffmin){
                return AjaxResult.error("打卡时间间隔未达到"+config.getValue()+"小时");
            }
        }
        clock.setClockDate(DateUtils.dateTime());
        List<BaseUserClock>  list=baseUserClockService.selectBaseUserClockList(clock);
        if(list.size()>0){
            BaseUserClock oldClick=list.get(0);
            Long diffSeconds=(DateUtils.getNowDate().getTime()-oldClick.getClockTime().getTime())/1000;
            if(Long.valueOf(config.getValue())*3600<=diffSeconds){
                clock.setClockTime(DateUtils.getNowDate());
                baseUserClockService.insertBaseUserClock(clock);
                BaseUser newUser=new BaseUser();
                newUser.setUserId(userId);
                newUser.setClickStatus("02");
                newUser.setClickTime(DateUtils.getNowDate());
                newUser.setUpdateBy(getUsername());
                newUser.setUpdateTime(DateUtils.getNowDate());
                newUser.setStatus("01");
                userInfoService.updateBaseUser(newUser);
            }else{
                return AjaxResult.error("打卡时间间隔未达到"+config.getValue()+"小时");
            }
            return AjaxResult.success("打卡成功！");
        }
        clock.setClockTime(DateUtils.getNowDate());
        baseUserClockService.insertBaseUserClock(clock);
        BaseUser newUser=new BaseUser();
        newUser.setUserId(userId);
        newUser.setClickStatus("02");
        newUser.setStatus("01");
        newUser.setClickTime(DateUtils.getNowDate());
        newUser.setUpdateBy(getUsername());
        newUser.setUpdateTime(DateUtils.getNowDate());
        userInfoService.updateBaseUser(newUser);
        return AjaxResult.success("打卡成功");
    }

    @GetMapping("/user/setResumeStatus")
    public AjaxResult setResumeStatus() {
        BaseUser userInfo=userInfoService.selectBaseUserByUserId(getUserId());
        BaseUser newUser=new BaseUser();
        newUser.setUserId(userInfo.getUserId());
        if("01".equals(userInfo.getStatus())){
            newUser.setStatus("02");
        }else{
            BaseUserResume userResume= baseUserResumeService.selectBaseUserResumeByUserId(userInfo.getUserId());
            BaseUserIntention userIntention=baseUserIntentionService.selectBaseUserIntentionByUserId(userInfo.getUserId());
            if(StringUtils.isEmpty(userResume.getIntroduction()) || StringUtils.isEmpty(userInfo.getAvatar()) || userIntention==null){
                return AjaxResult.error("请完善简历信息！");
            }
            newUser.setClickStatus("02");
            newUser.setClickTime(DateUtils.getNowDate());
            newUser.setStatus("01");
        }
        newUser.setUpdateBy(getUsername());
        newUser.setUpdateTime(DateUtils.getNowDate());
        userInfoService.updateBaseUser(newUser);
        return AjaxResult.success("操作成功");
    }


    @PostMapping("/user/userAuth")
    public AjaxResult userAuth(@RequestBody BaseUser userInfo) {
        if("02".equals(userInfo.getAuthType())){
            if(StringUtils.isEmpty(userInfo.getCertImage1())){
                return AjaxResult.error("请上传正面身份证照片");
            }
            if(StringUtils.isEmpty(userInfo.getCertImage2())){
                return AjaxResult.error("请上传反面身份证照片");
            }
        }
        else if("03".equals(userInfo.getAuthType())){
            if(StringUtils.isEmpty(userInfo.getCertImage1())){
                return AjaxResult.error("请上传正面身份证照片");
            }
        }else{
            return AjaxResult.error("参数传递错误");
        }
        if(StringUtils.isEmpty(userInfo.getAuthName())){
            return AjaxResult.error("认证姓名识别失败");
        }
        if(StringUtils.isEmpty(userInfo.getCertCode())){
            return AjaxResult.error("身份证号识别失败");
        }
        if(StringUtils.isEmpty(userInfo.getCertEndDate())){
            return AjaxResult.error("身份证有效期识别失败");
        }else{
            if(NumberUtil.isNumber(userInfo.getCertEndDate())){
                Date endDate=DateUtils.dateTime("yyyyMMdd", userInfo.getCertEndDate());
                if(endDate.getTime()<=DateUtils.getNowDate().getTime()){
                    return AjaxResult.error("身份证已过期");
                }
            }
        }
        if(StringUtils.isEmpty(userInfo.getNativePlace())){
            return AjaxResult.error("籍贯识别失败");
        }
        BaseUser checkUser= userInfoService.selectUserByUserCertCode(userInfo.getCertCode());
        if(checkUser!=null && checkUser.getUserId().intValue()!=getUserId().intValue()){
            return AjaxResult.error("身份证号已经存在");
        }
        userInfo.setUserId(getUserId());
        userInfo.setUpdateBy(getUsername());
        userInfo.setAuthStatus("02");
        userInfo.setStatus("01");
        userInfo.setAuthTime(DateUtils.getNowDate());
        userInfoService.updateBaseUser(userInfo);
        return AjaxResult.success("认证成功");
    }

    @PostMapping("/user/companyAuth")
    public AjaxResult companyAuth(@RequestBody BaseCompany company) {

        Long userId=getUserId();
        Long userCompnayId=getLoginUser().getUserInfo().getCompanyId();
        BaseCompany companyData=null;
        if(userCompnayId!=null){
            BaseCompany userCompany= baseCompanyService.selectBaseCompanyById(userCompnayId);
            if(userCompany!=null){
                companyData=userCompany;
            }else{
                companyData=baseCompanyService.selectBaseCompanyByUserId(userId);
            }
        }
        if(companyData==null){
            companyData=baseCompanyService.selectBaseCompanyByLienceCode(company.getBusinessLicenseCode());
        }
        if(companyData==null){
            companyData=baseCompanyService.selectBaseCompanyByName(company.getCompanyName());
        }
        if(companyData!=null){
            companyData.setAuthStatus("01");
            companyData.setShortName(company.getShortName());
            companyData.setCompanyName(company.getCompanyName());
            companyData.setBusinessLicenseUrl(company.getBusinessLicenseUrl());
            companyData.setSealUrl(company.getSealUrl());
            companyData.setContactName(company.getContactName());
            companyData.setContactPhone(company.getContactPhone());
            companyData.setUpdateBy(getUsername());
            companyData.setUpdateTime(DateUtils.getNowDate());
            baseCompanyService.updateBaseCompany(companyData);

        }else{
            companyData=company;
            companyData.setUserId(userId);
            companyData.setAuthStatus("01");
            companyData.setUpdateBy(getUsername());
            companyData.setUpdateTime(DateUtils.getNowDate());
            baseCompanyService.insertBaseCompany(companyData);
        }
        baseCompanyAddressService.deleteBaseCompanyAddressByCompanyId(companyData.getId());
        List<BaseCompanyAddress> addressList=company.getAdddressList();
        if(addressList.size()>0){
            for(BaseCompanyAddress addr : addressList){
                addr.setCompanyId(companyData.getId());
                baseCompanyAddressService.insertBaseCompanyAddress(addr);
            }
        }
        BaseUser userInfo=userInfoService.selectBaseUserByUserId(userId);
        userInfo.setCompanyName(companyData.getCompanyName());
        userInfo.setCompanyId(companyData.getId());
        userInfo.setAuthType("01");
        userInfo.setAuthStatus("01");
        userInfo.setAuthTime(DateUtils.getNowDate());
        userInfoService.updateBaseUser(userInfo);
        return AjaxResult.success("已提交认证申请，请耐心等待！");
    }

    @PostMapping("/user/addEvaluate")
    public AjaxResult addEvaluate(@Validated @RequestBody UserEvaluate userEvaluate) {
        BaseContract contractInfo= baseContractService.selectBaseContractById(userEvaluate.getContractId());
        if(contractInfo==null){
            return AjaxResult.error("合同不存在");
        }
        userEvaluate.setEvaluateUserId(getUserId());
        UserEvaluate param = new UserEvaluate();
        param.setContractId(userEvaluate.getContractId());
        param.setEvaluateUserId(userEvaluate.getEvaluateUserId());
        BaseUser evaluateUser = userInfoService.selectBaseUserByUserId(userEvaluate.getEvaluateUserId());
        if ("01".equals(evaluateUser.getUserType()) || "02".equals(evaluateUser.getUserType()) || "05".equals(evaluateUser.getUserType())) {
            userEvaluate.setType("02");
        }else if ("03".equals(evaluateUser.getUserType())){
            userEvaluate.setType("01");
        }else{
            return AjaxResult.error("只有雇主或者中介才能进行评价");
        }
        userEvaluate.setUserId(contractInfo.getBuserId());
        userEvaluate.setCreateBy(getUsername());
        userEvaluate.setEvaluateUserName(evaluateUser.getAuthName());
        userEvaluate.setEvaluateUserAvatar(evaluateUser.getAvatar());
        List<UserEvaluate> list = userEvaluateService.selectUserEvaluateList(param);
        if (list.size() > 0) {
            return AjaxResult.error("一个人只能评价一次");
        }
        int result = userEvaluateService.insertUserEvaluate(userEvaluate);
        return toAjax(result);
    }

    @GetMapping("/user/getEvaluateByContractId")
    public AjaxResult getEvaluateByContractId(@RequestParam(value = "id", required = true) Long id) {
        UserEvaluate param = new UserEvaluate();
        param.setContractId(id);
        List<UserEvaluate> list = userEvaluateService.selectUserEvaluateList(param);
        return AjaxResult.success(list);
    }


    @GetMapping("/user/getUserEvaluateData")
    public AjaxResult getUserEvaluateData(@RequestParam(value = "id", required = true) Long id) {
        UserEvaluate param = new UserEvaluate();
        param.setUserId(id);
        List<UserEvaluate> list = userEvaluateService.selectUserEvaluateList(param);
        if(list!=null) {
            list.stream().forEach(evaluate -> {
                String name = evaluate.getEvaluateUserName();
                if (StringUtils.isNotEmpty(name)) {
                    if (name.length() <= 1) {
                        evaluate.setEvaluateUserName(name);
                    } else {
                        name = name.substring(0, 1) + "*" + name.substring(name.length() - 1);
                        evaluate.setEvaluateUserName(name);
                    }
                }

            });
        }
        return AjaxResult.success(list);
    }

    @GetMapping("/user/getUserMessage")
    public AjaxResult getUserMessage(UserMessage userMessage) {
        BaseUser userInfo= getLoginUser().getUserInfo();
        SysNotice notice=new SysNotice();
        if("01".equals(userInfo.getUserType())||"02".equals(userInfo.getUserType())||"05".equals(userInfo.getUserType())){
            notice.setType("03");
        }
        else if("03".equals(userInfo.getUserType())){
            notice.setType("01");
        }
        else if("04".equals(userInfo.getUserType())){
            notice.setType("02");
        }

        notice.setStatus("0");
        List<SysNotice>  noticeList=noticeService.selectNoticeList(notice);
        userMessage.setUserId(userInfo.getUserId());
        List<UserMessage> messageList=userMessageService.selectUserMessageList(userMessage);
        TableDataInfo dataInfo=getDataTable(messageList);
        AjaxResult result= AjaxResult.success();
        result.put("noticeData",noticeList);
        result.put("total",dataInfo.getTotal());
        result.put("messageData",dataInfo.getRows());
        return result;
    }

    @GetMapping("/user/readAllUserMessage")
    public AjaxResult readAllUserMessage() {
        userMessageService.readAllUserMessageList(getUserId());
        return AjaxResult.success("操作成功");
    }

    @GetMapping("/user/readUserMessage")
    public AjaxResult readUserMessage(@RequestParam(value = "id", required = true) String id) {
        UserMessage msg= userMessageService.selectUserMessageById(id);
        if(msg!=null){
            msg.setReadStatus("Y");
            msg.setUpdateBy(getUsername());
            msg.setUpdateTime(DateUtils.getNowDate());
            msg.setReadTime(DateUtils.getNowDate());
            userMessageService.updateUserMessage(msg);
        }
        return AjaxResult.success("操作成功");
    }

    @GetMapping("/user/userLogout")
    public AjaxResult userLogout() {
        BaseUser loginUser=getLoginUser().getUserInfo();
        if(loginUser.getUserId().intValue()==1){
            return AjaxResult.error("平台管理员不允许注销");
        }

        if("01".equals(loginUser.getUserType()) || "02".equals(loginUser.getUserType())){
            return AjaxResult.error("公司用户不允许注销");
        }
        if("05".equals(loginUser.getUserType())){
            List<BaseUser> userList=userInfoService.selectBaseUserByAuthUserId(loginUser.getUserId());
            if(userList.size()>0){
                return AjaxResult.error("还有名下授权的雇主阿姨不允许注销！");
            }
        }
        if("02".equals(loginUser.getPublishType())){

        }
        baseUserResumeCertificateService.deleteResumeCertificateByCertCode(loginUser.getCertCode());
        baseUserResumeExperienceService.deleteResumeExperienceByCertCode(loginUser.getCertCode());
        baseUserResumeService.deleteBaseUserResumeByUserId(loginUser.getUserId());
        baseUserResumeService.deleteBaseUserResumeByCertCode(loginUser.getCertCode());
        baseUserFocusService.deleteBaseUserFocusByUserId(loginUser.getUserId());
        baseUserIntentionService.deleteBaseUserIntentionByUserId(loginUser.getUserId());
        userMessageService.deleteUserMessageByUserId(loginUser.getUserId());
        userInfoService.deleteBaseUserByUserId(loginUser.getUserId());
        baseAppointmentService.updateBaseAppointmentOffLine(loginUser.getUserId());
        return AjaxResult.success("注销成功");
    }

    @GetMapping("/user/changeUserPhone")
    public AjaxResult changeUserPhone(@RequestParam(value = "userPhone", required = true) String userPhone,
                                      @RequestParam(value = "code", required = true) String code) {
        if(StringUtils.isEmpty(userPhone)){
            return AjaxResult.error("手机号不能为空");
        }
        if(StringUtils.isEmpty(code)){
            return AjaxResult.error("验证码不能为空");
        }

        //演示环境注释掉了这段代码，正式环境需要放开
       /* String key = "phone_verify_code" + userPhone;
        String userCode = redisCache.getCacheObject(key) + "";
        if (!userCode.equals(code)) {
            return AjaxResult.error("验证码错误");
        }*/

        BaseUser currentUser = getLoginUser().getUserInfo();
        BaseUser checkUser= userInfoService.selectUserByUserName(userPhone);
        if(checkUser!=null){
            return AjaxResult.error("手机号已经被使用,请更换手机号");
        }
        currentUser.setUserName(userPhone);
        currentUser.setPhonenumber(userPhone);
        currentUser.setUpdateTime(DateUtils.getNowDate());
        int resultRow= userInfoService.updateBaseUser(currentUser);
        if(resultRow>0){
            return AjaxResult.success("操作成功");
        }else{
            return AjaxResult.error("操作失败");
        }
    }


    @GetMapping("/user/queryUserInfo")
    public TableDataInfo queryUserData(BaseUser user) {
        List<BaseUser> dataList= userInfoService.queryUserInfo(user);
        return getDataTable(dataList);
    }

}
